import 'dart:async';
import 'package:flutter/material.dart';
import '../services/auth_service.dart';
import '../config/app_config.dart';

/// 🔐 登录页面
/// 
/// 功能:
/// - 手机号登录
/// - 验证码发送
/// - 倒计时
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _authService = AuthService(AppConfig.serverUrl);
  final _phoneController = TextEditingController();
  final _codeController = TextEditingController();

  bool _codeSent = false;
  String? _verificationId;
  int _countdown = 0;
  Timer? _timer;
  bool _isLoading = false;

  @override
  void dispose() {
    _phoneController.dispose();
    _codeController.dispose();
    _timer?.cancel();
    super.dispose();
  }

  /// 发送验证码
  Future<void> _sendCode() async {
    final phone = _phoneController.text.trim();

    if (phone.isEmpty || phone.length != 11) {
      _showError('请输入正确的11位手机号');
      return;
    }

    setState(() {
      _isLoading = true;
    });

    final (success, verificationId, message) = await _authService.sendCode(phone);

    setState(() {
      _isLoading = false;
    });

    if (success && verificationId != null) {
      setState(() {
        _codeSent = true;
        _verificationId = verificationId;
        _countdown = 60;
      });

      // 启动倒计时
      _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        setState(() {
          if (_countdown > 0) {
            _countdown--;
          } else {
            timer.cancel();
          }
        });
      });

      _showSuccess(message);
    } else {
      _showError(message);
    }
  }

  /// 登录
  Future<void> _login() async {
    final phone = _phoneController.text.trim();
    final code = _codeController.text.trim();

    if (phone.isEmpty || phone.length != 11) {
      _showError('请输入正确的手机号');
      return;
    }

    if (code.isEmpty || code.length != 6) {
      _showError('请输入6位验证码');
      return;
    }

    if (_verificationId == null) {
      _showError('请先发送验证码');
      return;
    }

    setState(() {
      _isLoading = true;
    });

    final (success, userId, message) = await _authService.login(
      phoneNumber: phone,
      code: code,
      verificationId: _verificationId!,
    );

    setState(() {
      _isLoading = false;
    });

    if (success) {
      _showSuccess(message);
      // 登录成功，跳转到主页
      if (mounted) {
        Navigator.of(context).pushReplacementNamed('/main');
      }
    } else {
      _showError(message);
    }
  }

  /// 显示错误消息
  void _showError(String message) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }

  /// 显示成功消息
  void _showSuccess(String message) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('登录'),
        centerTitle: true,
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              const SizedBox(height: 40),
              
              // 标题
              const Text(
                '手机号登录',
                style: TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              const Text(
                '请输入手机号获取验证码',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey,
                ),
              ),
              
              const SizedBox(height: 40),
              
              // 手机号输入框
              TextField(
                controller: _phoneController,
                decoration: InputDecoration(
                  labelText: '手机号',
                  hintText: '请输入11位手机号',
                  prefixIcon: const Icon(Icons.phone),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                keyboardType: TextInputType.phone,
                maxLength: 11,
                enabled: !_isLoading,
              ),
              
              const SizedBox(height: 16),
              
              // 验证码输入框 + 发送按钮
              Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: TextField(
                      controller: _codeController,
                      decoration: InputDecoration(
                        labelText: '验证码',
                        hintText: '请输入6位验证码',
                        prefixIcon: const Icon(Icons.shield),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                      keyboardType: TextInputType.number,
                      maxLength: 6,
                      enabled: _codeSent && !_isLoading,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    flex: 1,
                    child: ElevatedButton(
                      onPressed: (_countdown > 0 || _isLoading) ? null : _sendCode,
                      style: ElevatedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 20),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                      child: Text(
                        _countdown > 0 ? '$_countdown秒' : '获取验证码',
                        style: const TextStyle(fontSize: 12),
                      ),
                    ),
                  ),
                ],
              ),
              
              const SizedBox(height: 32),
              
              // 登录按钮
              ElevatedButton(
                onPressed: (_codeSent && !_isLoading) ? _login : null,
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                child: _isLoading
                    ? const SizedBox(
                        height: 20,
                        width: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      )
                    : const Text(
                        '登录',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
              ),
              
              const Spacer(),
              
              // 提示文本
              Center(
                child: Text(
                  '登录即表示同意用户协议和隐私政策',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
